package com.yvon.service.demo.netty.nio.bytebuffer;

import com.yvon.service.demo.netty.utils.ByteBufferUtil;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.SQLOutput;


/**
 * @author : Yvon
 * @since : 2022-06-15
 */
public class ByteBufferTest {

    public static void main(String[] args) {
//        try (RandomAccessFile file = new RandomAccessFile("helloword/3parts.txt", "rw")) {
//            FileChannel channel = file.getChannel();
//            ByteBuffer d = ByteBuffer.allocate(4);
//            ByteBuffer e = ByteBuffer.allocate(4);
//            channel.position(11);
//
//            d.put(new byte[]{'f', 'o', 'u', 'r'});
//            e.put(new byte[]{'f', 'i', 'v', 'e'});
//            d.flip();
//            e.flip();
//            debugAll(d);
//            debugAll(e);
//            channel.write(new ByteBuffer[]{d, e});
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        ByteBuffer source = ByteBuffer.allocate(32);
        source.put("Hello,world\nI`m zhangsan \nHo".getBytes());
        split(source);
        source.put("ow are you?\nhaha!\n".getBytes());
        split(source);

    }
    private static void split(ByteBuffer source) {
        source.flip();
        int oldLimit = source.limit();
        for (int i =0; i < oldLimit; i++) {
            if (source.get(i) == '\n') {
                System.out.println(i);
                ByteBuffer target = ByteBuffer.allocate(i + 1 - source.position());
                source.limit(i+1);
                target.put(source);
                ByteBufferUtil.debugAll(target);
                source.limit(oldLimit);
            }
        }
        source.compact();
    }
}
